package com.haiyou.common.valid.aop;

import com.haiyou.common.valid.strategy.ContextStrategy;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * 检测控制层参数验证
 */
@Aspect
@Component
@Slf4j
@Order(1)
public class ParameterValidAspect {

    @Before(value = "execution(* com.*..controller.*.*(..))")
    public void beforeMethod(JoinPoint joinPoint) {
        log.debug("ParameterValidAspect代理类开始............");
        Object[] args = joinPoint.getArgs();
        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        //获取该方法在参数上的注解，每个参数可以有多个注解，得到的是一个二维数组
        Annotation[][] parameterAnnotations = method.getParameterAnnotations();
        for (int i = 0, iSize = parameterAnnotations.length; i < iSize; i++) {
            Annotation[] oneParameterAnnotations = parameterAnnotations[i];
            for (int j = 0, jSize = oneParameterAnnotations.length; j < jSize; j++) {
                Class<? extends Annotation> aClass = oneParameterAnnotations[j].annotationType();
                ContextStrategy.getInstance().executeStrategy(aClass.getSimpleName(), args[i], oneParameterAnnotations[j]);
            }
        }
    }


}
